import axios from "axios";
import browser from "webextension-polyfill"; // 跨浏览器兼容库

// 创建基础实例
const service = axios.create({
  timeout: 15000,
  baseURL: "http://localhost:8080",
  headers: {
    "X-Extension-Version": browser.runtime.getManifest().version,
  },
});

// 请求拦截器
service.interceptors.request.use(
  async (config) => {
    // 从插件存储获取认证信息
    const { authToken } = await browser.storage.local.get("authToken");
    if (authToken) {
      config.headers.Authorization = `Bearer ${authToken}`;
    }

    // 处理插件特殊请求类型
    if (config.chromeApi) {
      config.adapter = chromeApiAdapter;
    }

    return config;
  },
  (error) => Promise.reject(error)
);

// 响应拦截器
service.interceptors.response.use(
  (response) => response.data,
  (error) => {
    handleError(error);
    return Promise.reject(error);
  }
);

// Chrome API 适配器（用于绕过CSP限制）
const chromeApiAdapter = (config) => {
  return new Promise((resolve, reject) => {
    chrome.runtime.sendMessage(
      {
        type: "chromeRequest",
        config: {
          url: config.url,
          method: config.method,
          data: config.data,
          headers: config.headers,
        },
      },
      (response) => {
        if (chrome.runtime.lastError) {
          return reject(chrome.runtime.lastError);
        }
        resolve({
          data: response.data,
          status: response.status,
          headers: response.headers,
        });
      }
    );
  });
};

// 统一错误处理
function handleError(error) {
  if (error.response) {
    console.error(`[Axios Error] Status: ${error.response.status}`);
    if (error.response.status === 401) {
      browser.runtime.sendMessage({ type: "AUTH_EXPIRED" });
    }
  } else {
    console.error("[Network Error]", error.message);
  }

  // 发送错误通知
  browser.notifications.create({
    type: "basic",
    title: "请求错误",
    message: error.message || "未知网络错误",
    iconUrl: "icons/error-48.png",
  });
}

// 封装请求方法
export const chromeRequest = service;
